package handler

import (
	"github.com/gin-gonic/gin"
	pm "lab-service/proto/message"
	"net/http"
)

type Message struct {
	MessageClient pm.MessageService
}

func (m *Message) One(ctx *gin.Context) {
	form := new(pm.MessageRequest)
	if err := ctx.Bind(form); err != nil {
		ctx.AbortWithStatus(http.StatusBadRequest)
		return
	}

	rsp, err := m.MessageClient.One(ctx, form)
	if err != nil {
		ctx.AbortWithStatusJSON(http.StatusBadRequest, err)
		return
	}

	ctx.JSON(http.StatusOK, rsp)
}

func (m *Message) Page(ctx *gin.Context) {
	form := new(pm.MessageRequest)
	if err := ctx.Bind(form); err != nil {
		ctx.AbortWithStatus(http.StatusBadRequest)
		return
	}
	form.Enable = true
	form.Public = true

	rsp, err := m.MessageClient.Page(ctx, form)
	if err != nil {
		ctx.AbortWithStatusJSON(http.StatusBadRequest, err)
		return
	}

	ctx.JSON(http.StatusOK, rsp)
}

// only admin
func (m *Message) PageAll(ctx *gin.Context) {
	form := new(pm.MessageRequest)
	if err := ctx.Bind(form); err != nil {
		ctx.AbortWithStatus(http.StatusBadRequest)
		return
	}

	rsp, err := m.MessageClient.Page(ctx, form)
	if err != nil {
		ctx.AbortWithStatusJSON(http.StatusBadRequest, err)
		return
	}

	ctx.JSON(http.StatusOK, rsp)
}

// user with auth
func (m *Message) PageMe(ctx *gin.Context) {
	form := new(pm.MessageRequest)
	if err := ctx.Bind(form); err != nil {
		ctx.AbortWithStatus(http.StatusBadRequest)
		return
	}
	form.Uid = ctx.Value("uid").(int64)

	rsp, err := m.MessageClient.Page(ctx, form)
	if err != nil {
		ctx.AbortWithStatusJSON(http.StatusBadRequest, err)
		return
	}

	ctx.JSON(http.StatusOK, rsp)
}

func (m *Message) Create(ctx *gin.Context) {
	form := new(pm.MessageRequest)
	if err := ctx.Bind(form); err != nil {
		ctx.AbortWithStatus(http.StatusBadRequest)
		return
	}
	form.Uid = ctx.Value("uid").(int64)

	_, err := m.MessageClient.Create(ctx, form)
	if err != nil {
		ctx.AbortWithStatusJSON(http.StatusBadRequest, err)
		return
	}

	ctx.JSON(http.StatusOK, "success")
}

func (m *Message) CountMe(ctx *gin.Context) {
	rsp, err := m.MessageClient.CountMe(ctx, &pm.MessageRequest{
		Uid: ctx.Value("uid").(int64),
	})
	if err != nil {
		ctx.AbortWithStatusJSON(http.StatusBadRequest, err)
		return
	}

	ctx.JSON(http.StatusOK, rsp)
}

func (m *Message) Toggle(ctx *gin.Context) {
	form := new(pm.MessageRequest)
	if err := ctx.Bind(form); err != nil {
		ctx.AbortWithStatus(http.StatusBadRequest)
		return
	}

	_, err := m.MessageClient.Toggle(ctx, form)
	if err != nil {
		ctx.AbortWithStatusJSON(http.StatusBadRequest, err)
		return
	}

	ctx.JSON(http.StatusOK, "success")
}
